//
//  KSWebViewController.swift
//  Merchant
//
//  Created by liuxm on 2017/8/30.
//  Copyright © 2017年 huanniu. All rights reserved.
//

import UIKit
import WebKit

/// 加载网页
class KSWebViewController: KSBaseViewController, WKUIDelegate, WKNavigationDelegate {
    
    // URL地址
    var url: String?
    
    /// WKWebView对象
    fileprivate lazy var webView: WKWebView = {
        let web = WKWebView(frame: self.view.bounds)
        web.uiDelegate = self
        web.navigationDelegate = self
        web.backgroundColor = KSColor.kColorViewBackground
        web.isMultipleTouchEnabled = true
        web.autoresizesSubviews = true
        web.scrollView.alwaysBounceVertical = true
        web.allowsBackForwardNavigationGestures = true
        
        return web
    }()
    
    /// 进度条
    fileprivate lazy var progress:UIProgressView = {
        let progress = UIProgressView(frame: CGRect(x: 0, y: 0, width: KSConstants.kScreenWidth, height: 2))
        progress.tintColor = KSColor.kColorMainRed
        progress.backgroundColor = UIColor.white
        self.view.addSubview(progress)
        
        return progress
    }()
    
    /// 返还
    fileprivate var backBarBtn: UIBarButtonItem!
    /// 关闭
    fileprivate var closedBarBtn: UIBarButtonItem!
    /// 用来调整导航栏左右多个按钮间距
    fileprivate var navigationSpace:UIBarButtonItem!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.initView()
        self.addKVOObserver()
        self.loadRequest()
    }
    
    fileprivate func initView() {
        self.backBarBtn = UIBarButtonItem(image: UIImage.init(named: "Common_Back"), style: .plain, target: self, action: #selector(KSWebViewController.backBarBtnClick(sender:)))
        self.navigationSpace = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
        self.navigationSpace.width = -5
        self.closedBarBtn = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(KSWebViewController.closedBarBtnClick(sender:)))
        self.closedBarBtn?.imageInsets = UIEdgeInsetsMake(0, -20, 0, 20)
        
        let items = [self.navigationSpace, self.backBarBtn]
        self.navigationItem.leftBarButtonItems = items as? [UIBarButtonItem]
        
        self.view.addSubview(self.webView)
        self.view.addSubview(self.progress)
    }
    
    /// 返还
    ///
    /// - Parameter sender: sender
    @objc fileprivate func backBarBtnClick(sender: Any) {
        if self.webView.canGoBack {
            self.webView.goBack()
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    /// 关闭
    ///
    /// - Parameter sender: sender
    @objc fileprivate func closedBarBtnClick(sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    /// 添加观察者 作用：监听 加载进度值estimatedProgress、是否可以返回上一网页canGoBack、页面title
    fileprivate func addKVOObserver() {
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: [NSKeyValueObservingOptions.new,NSKeyValueObservingOptions.old], context: nil)
        self.webView.addObserver(self, forKeyPath: "canGoBack", options:[NSKeyValueObservingOptions.new,NSKeyValueObservingOptions.old], context: nil)
        self.webView.addObserver(self, forKeyPath: "title", options: [NSKeyValueObservingOptions.new,NSKeyValueObservingOptions.old], context: nil)
    }
    
    /// 加载网页
    fileprivate func loadRequest() {
        self.webView.load(NSURLRequest(url: URL(string: self.url!)!) as URLRequest)
    }
    
    /// 观察者的监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progress.alpha = 1.0
            self.progress .setProgress(Float(self.webView.estimatedProgress), animated: true)
            if self.webView.estimatedProgress >= 1 {
                UIView.animate(withDuration: 1.0, animations: {
                    self.progress.alpha = 0
                }, completion: { (finished) in
                    self.progress .setProgress(0.0, animated: false)
                })
            }
        } else if keyPath == "title" {
            self.navigationItem.title = self.webView.title
        } else if keyPath == "canGoBack" {
            if self.webView.canGoBack {
                let items = [self.navigationSpace, self.backBarBtn, self.closedBarBtn]
                self.navigationItem.leftBarButtonItems = items as? [UIBarButtonItem]
            } else {
                let items = [self.navigationSpace, self.backBarBtn]
                self.navigationItem.leftBarButtonItems = items as? [UIBarButtonItem]
            }
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
    
    // MARK: - WKNavigationDelegate
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        // 解决页面内调转到第三方页面打不开页面的问题
        if navigationAction.targetFrame == nil {
            self.webView.load(navigationAction.request)
        }
        
        decisionHandler(.allow)
    }
    
    deinit {
        // 移除观察者
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
        self.webView.removeObserver(self, forKeyPath: "canGoBack")
        self.webView.removeObserver(self, forKeyPath: "title")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
